package org.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

// 单例模式：游戏状态管理
class GameState {
    private static GameState instance;
    private int score;
    private int progress;
    private List<String> savedGames = new ArrayList<>();
    private String currentSkin = "default";
    private List<String> ownedSkins = new ArrayList<>();
    private List<String> inventory = new ArrayList<>();

    private GameState() {
        score = 0; // 初始0点
        progress = 0;
        savedGames.add("初始存档");
        ownedSkins.add("default");
    }

    public static synchronized GameState getInstance() {
        if (instance == null) {
            instance = new GameState();
        }
        return instance;
    }

    // Getter和Setter方法
    public int getScore() { return score; }
    public void setScore(int score) { this.score = score; }
    public int getProgress() { return progress; }
    public void setProgress(int progress) { this.progress = progress; }
    public List<String> getSavedGames() { return savedGames; }
    public void addSavedGame(String game) { savedGames.add(game); }
    public String getCurrentSkin() { return currentSkin; }
    public void setCurrentSkin(String skin) { this.currentSkin = skin; }
    public List<String> getOwnedSkins() { return ownedSkins; }
    public void addOwnedSkin(String skin) { ownedSkins.add(skin); }
    public List<String> getInventory() { return inventory; }
    public void addToInventory(String item) { inventory.add(item); }
}

// 策略模式：不同的修复策略
interface RepairStrategy {
    boolean repair(String code);
}

class BasicRepairStrategy implements RepairStrategy {
    @Override
    public boolean repair(String code) {
        return code.contains("System") && code.contains("reboot");
    }
}

class AdvancedRepairStrategy implements RepairStrategy {
    @Override
    public boolean repair(String code) {
        return code.contains("override") && code.contains("main");
    }
}

// 观察者模式：游戏状态变化
interface GameObserver {
    void update();
}

class ScoreObserver implements GameObserver {
    @Override
    public void update() {
        System.out.println("分数更新: " + GameState.getInstance().getScore());
    }
}

// 工厂模式：创建UI组件
class ComponentFactory {
    public static JButton createButton(String text, int x, int y, int width, int height) {
        JButton button = new JButton(text);
        button.setBounds(x, y, width, height);
        button.setForeground(Color.WHITE);
        button.setBackground(new Color(0, 0, 100));
        return button;
    }
    
    public static JLabel createLabel(String text, int x, int y, int width, int height, int fontSize) {
        JLabel label = new JLabel(text);
        label.setBounds(x, y, width, height);
        label.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
        return label;
    }
}

// 装饰器模式：皮肤定制
interface SkinDecorator {
    void applySkin(Component component);
}

class DefaultSkinDecorator implements SkinDecorator {
    @Override
    public void applySkin(Component component) {
        component.setBackground(Color.BLACK);
        if (component instanceof AbstractButton) {
            component.setForeground(Color.WHITE);
        }
    }
}

class BlueSkinDecorator implements SkinDecorator {
    @Override
    public void applySkin(Component component) {
        component.setBackground(new Color(0, 0, 100));
        if (component instanceof AbstractButton) {
            component.setForeground(Color.CYAN);
        }
    }
}

// 代理模式：访问敏感操作
interface GodAccess {
    boolean interfere(String code);
}

class GodAccessProxy implements GodAccess {
    private RealGodAccess realAccess = new RealGodAccess();
    
    @Override
    public boolean interfere(String code) {
        if (GameState.getInstance().getScore() < 0) {
            System.out.println("分数不足，无法干扰主神");
            return false;
        }
        return realAccess.interfere(code);
    }
}

class RealGodAccess implements GodAccess {
    @Override
    public boolean interfere(String code) {
        // 实际干扰逻辑
        return code.contains("god") && code.contains("override");
    }
}

public class CodeRebirthGame {
    private JFrame frame;
    private GameState gameState;
    private RepairStrategy currentRepairStrategy;
    private SkinDecorator currentSkinDecorator;
    private GodAccess godAccess;
    
    public CodeRebirthGame() {
        // 设置中文编码
        try {
            System.setProperty("file.encoding", "UTF-8");
            java.lang.reflect.Field charset = Charset.class.getDeclaredField("defaultCharset");
            charset.setAccessible(true);
            charset.set(null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        gameState = GameState.getInstance();
        currentRepairStrategy = new BasicRepairStrategy();
        currentSkinDecorator = new DefaultSkinDecorator();
        godAccess = new GodAccessProxy();
        
        initializeFrame();
        addObserver(new ScoreObserver());
    }
    
    private void initializeFrame() {
        frame = new JFrame("Code Rebirth: 系统觉醒");
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);
        frame.getContentPane().setBackground(Color.BLACK);
    }
    
    public void addObserver(GameObserver observer) {
        observer.update();
    }
    
    public void showLoginScreen() {
        frame.getContentPane().removeAll();
        
        JPanel loginPanel = new JPanel();
        loginPanel.setBounds(250, 150, 300, 300);
        loginPanel.setLayout(null);
        loginPanel.setBackground(new Color(0, 0, 100, 150));
        
        JLabel titleLabel = ComponentFactory.createLabel("系统登录", 50, 30, 200, 30, 20);
        titleLabel.setForeground(Color.WHITE);
        JLabel userLabel = ComponentFactory.createLabel("用户名:", 30, 80, 100, 20, 14);
        userLabel.setForeground(Color.WHITE);
        JTextField userField = new JTextField();
        userField.setBounds(130, 80, 140, 25);
        
        JLabel passLabel = ComponentFactory.createLabel("密码:", 30, 120, 100, 20, 14);
        passLabel.setForeground(Color.WHITE);
        JPasswordField passField = new JPasswordField();
        passField.setBounds(130, 120, 140, 25);
        
        JButton loginButton = ComponentFactory.createButton("登录", 100, 180, 100, 30);
        loginButton.setForeground(Color.BLACK);
        loginButton.addActionListener(e -> {
            // 简单登录验证
            if (String.valueOf(passField.getPassword()).length() > 0) {
                showMainMenu();
            }
        });
        
        loginPanel.add(titleLabel);
        loginPanel.add(userLabel);
        loginPanel.add(userField);
        loginPanel.add(passLabel);
        loginPanel.add(passField);
        loginPanel.add(loginButton);
        
        frame.add(loginPanel);
        frame.revalidate();
        frame.repaint();
        frame.setVisible(true);
    }
    
    public void showMainMenu() {
        frame.getContentPane().removeAll();
        
        // 动态标题
        JLabel title = new JLabel("Code Rebirth: 系统觉醒");
        title.setBounds(190, 50, 600, 70);
        title.setFont(new Font("微软雅黑", Font.BOLD, 50));
        
        // 创建渐变效果
        Timer titleTimer = new Timer(100, new ActionListener() {
            float hue = 0;
            @Override
            public void actionPerformed(ActionEvent e) {
                hue += 0.01f;
                if (hue > 1) hue = 0;
                Color color = Color.getHSBColor(hue, 0.8f, 0.8f);
                title.setForeground(color);
            }
        });
        titleTimer.start();
        
        // 菜单按钮
        JButton startButton = ComponentFactory.createButton("开始游戏", 40, 400, 120, 40);
        startButton.setForeground(Color.BLACK);
        JButton loadButton = ComponentFactory.createButton("加载存档", 40, 450, 120, 40);
        loadButton.setForeground(Color.BLACK);
        JButton exitButton = ComponentFactory.createButton("退出游戏", 40, 500, 120, 40);
        exitButton.setForeground(Color.BLACK);
        
        startButton.addActionListener(e -> showSecondScreen());
        loadButton.addActionListener(e -> showLoadScreen());
        exitButton.addActionListener(e -> System.exit(0));
        
        frame.add(title);
        frame.add(startButton);
        frame.add(loadButton);
        frame.add(exitButton);
        
        frame.revalidate();
        frame.repaint();
    }
    
    public void showSecondScreen() {
        frame.getContentPane().removeAll();
        // 第一张图片
        JLabel imageLabel = new JLabel(new ImageIcon("game1.jpg")); // 替换为实际图片路径
        imageLabel.setBounds(0, 0, 800, 600);
        frame.add(imageLabel);


        // 自动过渡计时器
        Timer timer = new Timer(5000, e -> transitionToThirdScreen());
        timer.setRepeats(false);
        timer.start();

        // 鼠标点击手动过渡
        imageLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                timer.stop();
                transitionToThirdScreen();
            }
        });

        frame.revalidate();
        frame.repaint();
    }

    private void transitionToThirdScreen() {
        frame.getContentPane().removeAll();

        // 第二张图片
        JLabel imageLabel = new JLabel(new ImageIcon("game2.jpg")); // 替换为实际图片路径
        imageLabel.setBounds(0, 0, 800, 600);
        imageLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                showThirdScreen();
            }
        });
        frame.add(imageLabel);

        frame.revalidate();
        frame.repaint();
    }


public void showThirdScreen() {
    frame.getContentPane().removeAll();
    frame.getContentPane().setBackground(Color.BLACK);

    // 调整面板尺寸和透明度
    JPanel panel = new JPanel();
    panel.setBounds(140, 240, 500, 100);
    panel.setBackground(new Color(0, 0, 255, 134));
    panel.setLayout(new BorderLayout());

    // 文本区域设置
    JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    textArea.setFont(new Font("微软雅黑", Font.BOLD, 16));
    textArea.setForeground(Color.WHITE);
    textArea.setBackground(new Color(0, 0, 0, 0));
    textArea.setFocusable(false);

    // 滚动面板透明化
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setOpaque(false);
    scrollPane.getViewport().setOpaque(false);
    panel.add(scrollPane, BorderLayout.CENTER);

    // 文字动画 - 使用数组绕过final限制
    final int[] charIndex = {0}; // 使用数组来绕过lambda表达式的final限制
    String fullText = "你（一个存款百万的程序员）因为过度劳累猝死了，睁眼发现自己变成了因为产生了自主意识被主神销毁而奄奄一息的系统...必须尽快修复自己...";

    Timer textTimer = new Timer(100, e -> {
        if (charIndex[0] < fullText.length()) {
            textArea.setText(fullText.substring(0, charIndex[0] + 1));
            charIndex[0]++;
        } else {
            ((Timer)e.getSource()).stop();
        }
    });
    textTimer.start();

    // 双重点击监听
    MouseAdapter clickListener = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            textTimer.stop();
            showFourthScreen();
        }
    };
    panel.addMouseListener(clickListener);
    textArea.addMouseListener(clickListener);

    frame.add(panel);
    frame.revalidate();
    frame.repaint();
}
    
    public void showFourthScreen() {
        frame.getContentPane().removeAll();
        
        // 类似第二屏但使用不同图片
        JLabel imageLabel = new JLabel(new ImageIcon("image3.jpg")); // 替换为实际图片路径
        imageLabel.setBounds(0, 0, 800, 600);
        frame.add(imageLabel);
        
        Timer timer = new Timer(5000, e -> transitionToFifthScreen());
        timer.setRepeats(false);
        timer.start();
        
        imageLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                timer.stop();
                transitionToFifthScreen();
            }
        });
        
        frame.revalidate();
        frame.repaint();
    }
    
    private void transitionToFifthScreen() {
        frame.getContentPane().removeAll();
        
        JLabel imageLabel = new JLabel(new ImageIcon("image4.jpg")); // 替换为实际图片路径
        imageLabel.setBounds(0, 0, 800, 600);
        imageLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                showFifthScreen();
            }
        });
        frame.add(imageLabel);
        
        frame.revalidate();
        frame.repaint();
    }
    
    public void showFifthScreen() {
        frame.getContentPane().removeAll();
        
        // 类似第三屏但使用不同文字
        frame.getContentPane().setBackground(Color.BLACK);

        JPanel panel = new JPanel();
        panel.setBounds(140, 240, 500, 100);
        panel.setBackground(new Color(0, 0, 255, 142));
        panel.setLayout(new BorderLayout());
        
        JTextArea textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setFont(new Font("微软雅黑", Font.BOLD, 16));
        textArea.setForeground(Color.WHITE);
        textArea.setBackground(new Color(0, 0, 0, 0));
        textArea.setFocusable(false);

        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        panel.add(scrollPane, BorderLayout.CENTER);
        
        String fullText = "你必须通过修复代码来恢复系统功能...小心不要被主神发现...";
        Timer textTimer = new Timer(100, new ActionListener() {
            int charIndex = 0;
            @Override
            public void actionPerformed(ActionEvent e) {
                if (charIndex < fullText.length()) {
                    textArea.setText(fullText.substring(0, charIndex + 1));
                    charIndex++;
                } else {
                    ((Timer)e.getSource()).stop();
                }
            }
        });
        textTimer.start();

        // 双重点击监听
        MouseAdapter clickListener = new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                textTimer.stop();
                showCodeScreen();
            }
        };
        panel.addMouseListener(clickListener);
        textArea.addMouseListener(clickListener);
    frame.add(panel);
        frame.revalidate();
        frame.repaint();
    }


public void showCodeScreen() {
    frame.getContentPane().removeAll();

    // 创建代码雨画布
    JPanel codeRainPanel = new JPanel() {
        private static final int COLUMN_COUNT = 80;
        private static final int FONT_SIZE = 25 ;
        private int[] columnPositions;
        private char[][] columnChars;
        private Font font = new Font("Monospaced", Font.PLAIN, FONT_SIZE);

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setFont(font);

            // 初始化列位置和字符
            if (columnPositions == null) {
                columnPositions = new int[COLUMN_COUNT];
                columnChars = new char[COLUMN_COUNT][];
                for (int i = 0; i < COLUMN_COUNT; i++) {
                    columnPositions[i] = (int) (Math.random() * getHeight());
                    int length = 5 + (int) (Math.random() * 15);
                    columnChars[i] = new char[length];
                    for (int j = 0; j < length; j++) {
                        columnChars[i][j] = getRandomChar();
                    }
                }
            }

            // 绘制所有列
            for (int i = 0; i < COLUMN_COUNT; i++) {
                int x = i * (getWidth() / COLUMN_COUNT);

                // 绘制列中的每个字符
                for (int j = 0; j < columnChars[i].length; j++) {
                    int y = (columnPositions[i] + j * FONT_SIZE) % (getHeight() + columnChars[i].length * FONT_SIZE);

                    // 第一个字符是白色，其他是绿色
                    if (j == 0) {
                        g2d.setColor(Color.WHITE);
                    } else {
                        float brightness = 0.3f + 0.7f * (1 - (float)j / columnChars[i].length);
                        g2d.setColor(new Color(0, (int)(brightness * 255), 0));
                    }

                    g2d.drawString(String.valueOf(columnChars[i][j]), x, y);
                }

                // 随机改变列位置和字符
                if (Math.random() < 0.05) {
                    columnPositions[i] = (int) (Math.random() * getHeight());
                }
                if (Math.random() < 0.02) {
                    columnChars[i][(int)(Math.random() * columnChars[i].length)] = getRandomChar();
                }
            }
        }

        private char getRandomChar() {
            // 随机返回一个ASCII字符(33-126)
            return (char) (33 + (int)(Math.random() * 94));
        }
    };

    codeRainPanel.setBackground(Color.BLACK);
    codeRainPanel.setBounds(0, 0, 800, 600);
    frame.add(codeRainPanel);

    // 动画定时器
    Timer animationTimer = new Timer(50, e -> {
        codeRainPanel.repaint();
    });
    animationTimer.start();

    // 5秒后显示保存/继续选项
    Timer optionTimer = new Timer(5000, e -> {
        animationTimer.stop();
        showSaveOptionPanel();
    });
    optionTimer.setRepeats(false);
    optionTimer.start();

    frame.revalidate();
    frame.repaint();
}
    
    private void showSaveOptionPanel() {
        JPanel panel = new JPanel();
        panel.setBounds(250, 200, 300, 200);
        panel.setBackground(new Color(0, 0, 255, 180));
        panel.setLayout(new GridLayout(2, 1, 10, 10));
        
        JButton saveButton = ComponentFactory.createButton("存档", 0, 0, 300, 50);
        saveButton.setForeground(Color.BLACK);
        JButton continueButton = ComponentFactory.createButton("继续游戏", 0, 0, 300, 50);
        continueButton.setForeground(Color.BLACK);
        
        saveButton.addActionListener(e -> {
            gameState.addSavedGame("进度存档-" + System.currentTimeMillis());
            JOptionPane.showMessageDialog(frame, "游戏已存档");
            showRepairScreen();
        });
        
        continueButton.addActionListener(e -> showRepairScreen());
        
        panel.add(saveButton);
        panel.add(continueButton);
        
        frame.add(panel);
        frame.revalidate();
        frame.repaint();
    }

// 修复题目列表
private String[] repairQuestions = {
        "修复题目: 如何重启系统? (提示: 包含System和reboot)",
        "修复题目: 如何初始化内存? (提示: 包含Memory和allocate)",
        "修复题目: 如何修复文件系统? (提示: 包含File和recover)",
        "修复题目: 如何重置网络连接? (提示: 包含Network和reset)",
        "修复题目: 如何恢复数据库? (提示: 包含Database和restore)"
};

    private int currentQuestionIndex = 0;
public void showRepairScreen() {
    frame.getContentPane().removeAll();

    // 黑色背景
    frame.getContentPane().setBackground(Color.BLACK);

    // 问题面板(半透明蓝色)
    JPanel questionPanel = new JPanel();
    questionPanel.setBounds(100, 50, 600, 150);
    questionPanel.setBackground(new Color(0, 0, 255, 100));
    questionPanel.setLayout(new BorderLayout());

    // 获取当前题目
    String currentQuestion = repairQuestions[currentQuestionIndex];
    JLabel questionLabel = new JLabel(currentQuestion);
    questionLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
    questionLabel.setForeground(Color.WHITE);
    questionPanel.add(questionLabel, BorderLayout.NORTH);

    // 代码输入区域
    JTextArea codeArea = new JTextArea();
    codeArea.setEditable(true);
    codeArea.setForeground(new Color(57, 255, 20)); // 荧光绿
    codeArea.setBackground(Color.BLACK);
    codeArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
    codeArea.setCaretColor(Color.GREEN);

    // 添加代码提示
    DefaultListModel<String> hintModel = new DefaultListModel<>();
    JList<String> hintList = new JList<>(hintModel);
    hintList.setVisibleRowCount(3);

    // 根据题目添加提示词
    switch(currentQuestionIndex) {
        case 0: // System reboot
            hintModel.addElement("System");
            hintModel.addElement("reboot");
            hintModel.addElement("System.out");
            break;
        case 1: // Memory allocate
            hintModel.addElement("Memory");
            hintModel.addElement("allocate");
            hintModel.addElement("free");
            break;
        case 2: // File recover
            hintModel.addElement("File");
            hintModel.addElement("recover");
            hintModel.addElement("read");
            break;
        case 3: // Network reset
            hintModel.addElement("Network");
            hintModel.addElement("reset");
            hintModel.addElement("connect");
            break;
        case 4: // Database restore
            hintModel.addElement("Database");
            hintModel.addElement("restore");
            hintModel.addElement("backup");
            break;
    }

    // 双击提示词插入代码
    hintList.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                String selected = hintList.getSelectedValue();
                if (selected != null) {
                    codeArea.insert(selected, codeArea.getCaretPosition());
                }
            }
        }
    });

    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
            new JScrollPane(codeArea),
            new JScrollPane(hintList));
    splitPane.setDividerLocation(100);
    questionPanel.add(splitPane, BorderLayout.CENTER);

    // 控制面板
    JPanel controlPanel = new JPanel();
    controlPanel.setBounds(100, 400, 600, 150);
    controlPanel.setBackground(new Color(0, 0, 0, 0));
    controlPanel.setLayout(new GridLayout(1, 4, 10, 10));

    JLabel scoreLabel = new JLabel("积分: " + gameState.getScore());
    scoreLabel.setForeground(Color.WHITE);
    scoreLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

    JButton hintButton = ComponentFactory.createButton("提示 (10积分)", 0, 0, 150, 40);
    hintButton.setForeground(Color.BLACK);
    JButton saveButton = ComponentFactory.createButton("保存进度", 0, 0, 150, 40);
    saveButton.setForeground(Color.BLACK);
    JButton submitButton = ComponentFactory.createButton("提交", 0, 0, 150, 40);
    submitButton.setForeground(Color.BLACK);

    hintButton.addActionListener(e -> {
        if (gameState.getScore() >= 10) {
            gameState.setScore(gameState.getScore() - 10);
            scoreLabel.setText("积分: " + gameState.getScore());

            // 提供更具体的提示
            String hint = "";
            switch(currentQuestionIndex) {
                case 0: hint = "尝试使用System类的静态方法"; break;
                case 1: hint = "需要分配内存空间"; break;
                case 2: hint = "检查文件恢复方法"; break;
                case 3: hint = "网络连接需要重置"; break;
                case 4: hint = "数据库需要从备份恢复"; break;
            }
            JOptionPane.showMessageDialog(frame, hint);
        } else {
            JOptionPane.showMessageDialog(frame, "积分不足!");
        }
    });

    saveButton.addActionListener(e -> {
        gameState.addSavedGame("修复进度存档-" + System.currentTimeMillis());
        JOptionPane.showMessageDialog(frame, "进度已保存");
    });

    submitButton.addActionListener(e -> {
        String code = codeArea.getText();
        boolean isCorrect = false;

        // 根据题目验证答案
        switch(currentQuestionIndex) {
            case 0:
                isCorrect = code.contains("System") && code.contains("reboot");
                break;
            case 1:
                isCorrect = code.contains("Memory") && code.contains("allocate");
                break;
            case 2:
                isCorrect = code.contains("File") && code.contains("recover");
                break;
            case 3:
                isCorrect = code.contains("Network") && code.contains("reset");
                break;
            case 4:
                isCorrect = code.contains("Database") && code.contains("restore");
                break;
        }

        if (isCorrect) {
            gameState.setScore(gameState.getScore() + 20);
            gameState.setProgress(gameState.getProgress() + 20);
            scoreLabel.setText("积分: " + gameState.getScore());

            // 移动到下一个题目或结束
            currentQuestionIndex = (currentQuestionIndex + 1) % repairQuestions.length;

            if (gameState.getProgress() >= 100) {
                showFinalScreen();
            } else {
                showProgressScreen();
            }
        } else {
            showAlertScreen();
        }
    });

    controlPanel.add(scoreLabel);
    controlPanel.add(hintButton);
    controlPanel.add(saveButton);
    controlPanel.add(submitButton);

    frame.add(questionPanel);
    frame.add(controlPanel);
    frame.revalidate();
    frame.repaint();
    codeArea.requestFocusInWindow();
}

public void showProgressScreen() {
    frame.getContentPane().removeAll();
    frame.getContentPane().setBackground(Color.BLACK);

    JPanel panel = new JPanel();
    panel.setBounds(200, 200, 400, 200);
    panel.setBackground(new Color(0, 0, 100, 150));
    panel.setLayout(new BorderLayout());

    JProgressBar progressBar = new JProgressBar(0, 100);
    progressBar.setValue(gameState.getProgress());
    progressBar.setStringPainted(true);
    progressBar.setForeground(new Color(0, 200, 0));
    progressBar.setBackground(new Color(50, 50, 50));
    progressBar.setFont(new Font("微软雅黑", Font.BOLD, 14));

    JLabel label = new JLabel("修复进度: " + gameState.getProgress() + "%", JLabel.CENTER);
    label.setForeground(Color.WHITE);
    label.setFont(new Font("微软雅黑", Font.BOLD, 16));

    panel.add(progressBar, BorderLayout.CENTER);
    panel.add(label, BorderLayout.SOUTH);

    // 8秒后自动进入下一个修复界面
    Timer timer = new Timer(8000, e -> {
        showRepairScreen();
    });
    timer.setRepeats(false);
    timer.start();

    // 点击鼠标可立即进入下一个修复界面
    panel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            timer.stop();
            showRepairScreen();
        }
    });

    frame.add(panel);
    frame.revalidate();
    frame.repaint();
}

    public void showAlertScreen() {
        frame.getContentPane().removeAll();
        
        // 警告三角形
        JPanel trianglePanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D)g;
                g2d.setColor(Color.RED);
                g2d.setStroke(new BasicStroke(5));
                
                int[] xPoints = {400, 200, 600};
                int[] yPoints = {100, 400, 400};
                g2d.drawPolygon(xPoints, yPoints, 3);
                
                g2d.setFont(new Font("微软雅黑", Font.BOLD, 60));
                g2d.drawString("!", 390, 300);
            }
        };
        trianglePanel.setBounds(0, 0, 800, 500);
        trianglePanel.setBackground(new Color(0, 0, 0, 0));
        
        // 警告文字
        JTextArea textArea = new JTextArea();
        textArea.setBounds(100, 450, 600, 100);
        textArea.setEditable(false);
        textArea.setFont(new Font("微软雅黑", Font.BOLD, 16));
        textArea.setForeground(Color.RED);
        textArea.setBackground(new Color(0, 0, 0, 0));
        
        // 警告文字动画
        String fullText = "警告! 你被主神发现了! 输入干扰代码自救...";
        Timer textTimer = new Timer(150, new ActionListener() {
            int charIndex = 0;
            @Override
            public void actionPerformed(ActionEvent e) {
                if (charIndex < fullText.length()) {
                    textArea.setText(fullText.substring(0, charIndex + 1));
                    charIndex++;
                } else {
                    ((Timer)e.getSource()).stop();
                    showInterferenceScreen();
                }
            }
        });
        textTimer.start();
        
        frame.add(trianglePanel);
        frame.add(textArea);
        frame.revalidate();
        frame.repaint();
    }

public void showInterferenceScreen() {
    frame.getContentPane().removeAll();

    // 类似修复界面但使用红色
    JPanel questionPanel = new JPanel();
    questionPanel.setBounds(100, 50, 600, 150);
    questionPanel.setBackground(new Color(255, 0, 0, 100));
    questionPanel.setLayout(new BorderLayout());

    JLabel questionLabel = new JLabel("干扰题目: 如何干扰主神? (提示: 包含god和override)");
    questionLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
    questionLabel.setForeground(Color.WHITE);
    questionPanel.add(questionLabel, BorderLayout.NORTH);

    JTextArea codeArea = new JTextArea();
    codeArea.setForeground(Color.GREEN);
    codeArea.setBackground(Color.BLACK);
    codeArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
    questionPanel.add(new JScrollPane(codeArea), BorderLayout.CENTER);

    // 控制面板
    JPanel controlPanel = new JPanel();
    controlPanel.setBounds(100, 400, 600, 150);
    controlPanel.setBackground(new Color(0, 0, 0, 0));
    controlPanel.setLayout(new GridLayout(1, 3, 10, 10));

    JLabel scoreLabel = new JLabel("积分: " + gameState.getScore());
    scoreLabel.setForeground(Color.WHITE);
    scoreLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

    JButton hintButton = ComponentFactory.createButton("提示 (10积分)", 0, 0, 150, 40);
    hintButton.setForeground(Color.BLACK);
    JButton saveButton = ComponentFactory.createButton("保存进度", 0, 0, 150, 40);
    saveButton.setForeground(Color.BLACK);
    JButton submitButton = ComponentFactory.createButton("提交", 0, 0, 150, 40);
    submitButton.setForeground(Color.BLACK);


    hintButton.addActionListener(e -> {
        if (gameState.getScore() >= 10) {
            gameState.setScore(gameState.getScore() - 10);
            scoreLabel.setText("积分: " + gameState.getScore());
            JOptionPane.showMessageDialog(frame, "提示: 需要覆盖主神的方法");
        } else {
            JOptionPane.showMessageDialog(frame, "积分不足!");
        }
    });

    saveButton.addActionListener(e -> {
        gameState.addSavedGame("干扰进度存档-" + System.currentTimeMillis());
        JOptionPane.showMessageDialog(frame, "进度已保存");
    });

    submitButton.addActionListener(e -> {
        String code = codeArea.getText();
        if (godAccess.interfere(code)) {
            JOptionPane.showMessageDialog(frame, "干扰成功! 返回修复界面");
            showRepairScreen();
        } else {
            showSystemDestruction(); // 替换原来的JOptionPane
        }
    });

    controlPanel.add(scoreLabel);
    controlPanel.add(hintButton);
    controlPanel.add(saveButton);
    controlPanel.add(submitButton);

    frame.add(questionPanel);
    frame.add(controlPanel);
    frame.revalidate();
    frame.repaint();
}

// 显示系统销毁动画
public void showSystemDestruction() {
    frame.getContentPane().removeAll();
    frame.getContentPane().setBackground(Color.BLACK);

    // 创建红色字幕标签
    JLabel destructionLabel = new JLabel("", JLabel.CENTER);
    destructionLabel.setFont(new Font("微软雅黑", Font.BOLD, 30));
    destructionLabel.setForeground(new Color(255, 50, 50)); // 暗红色
    destructionLabel.setBounds(0, 250, 800, 100);

    frame.add(destructionLabel);
    frame.revalidate();
    frame.repaint();

    // 要显示的销毁文本
    String destructionText = "警告！系统核心遭到主神反制...\n正在发生不可逆的销毁...";
    Timer destructionTimer = new Timer(120, new ActionListener() {
        int charIndex = 0;
        int lineBreakPos = destructionText.indexOf('\n');

        @Override
        public void actionPerformed(ActionEvent e) {
            if (charIndex < destructionText.length()) {
                // 逐字显示文本
                destructionLabel.setText(destructionText.substring(0, charIndex + 1));
                charIndex++;

                // 第一行显示完后稍作停顿
                if (charIndex == lineBreakPos) {
                    ((Timer)e.getSource()).setDelay(700);
                } else if (charIndex > lineBreakPos) {
                    ((Timer)e.getSource()).setDelay(120);
                }
            } else {
                ((Timer)e.getSource()).stop();
                // 文本显示完成后进入最终销毁画面
                showFinalDestruction();
            }
        }
    });
    destructionTimer.start();
}

    // 显示最终销毁画面
    private void showFinalDestruction() {
        frame.getContentPane().removeAll();

        // 创建销毁画面面板
        JPanel destructionPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D)g;

                // 绘制裂纹效果背景
                g2d.setColor(new Color(30, 0, 0));
                g2d.fillRect(0, 0, getWidth(), getHeight());

                // 绘制红色裂纹
                g2d.setColor(new Color(200, 0, 0, 150));
                g2d.setStroke(new BasicStroke(3));
                // 随机裂纹线条
                for (int i = 0; i < 10; i++) {
                    int x1 = (int)(Math.random() * getWidth());
                    int y1 = (int)(Math.random() * getHeight());
                    int x2 = (int)(Math.random() * getWidth());
                    int y2 = (int)(Math.random() * getHeight());
                    g2d.drawLine(x1, y1, x2, y2);
                }

                // 绘制系统销毁图标
                g2d.setColor(Color.RED);
                g2d.setFont(new Font("微软雅黑", Font.BOLD, 100));
                g2d.drawString("☠", 350, 300); // 骷髅图标

                // 绘制提示文本
                g2d.setFont(new Font("微软雅黑", Font.BOLD, 24));
                g2d.drawString("系统已终止 - 点击返回登录界面", 250, 400);
            }
        };

        destructionPanel.setBounds(0, 0, 800, 600);
        destructionPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // 点击后返回首页
                showMainMenu();
            }
        });

        frame.add(destructionPanel);
        frame.revalidate();
        frame.repaint();
    }

    private void showDestructionImage() {
        frame.getContentPane().removeAll();

        // 显示销毁图片
        JLabel imageLabel = new JLabel(new ImageIcon("destruction.jpg")); // 替换为实际图片路径
        imageLabel.setBounds(0, 0, 800, 600);

        // 点击返回登录界面
        imageLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                showLoginScreen();
            }
        });

        frame.add(imageLabel);
        frame.revalidate();
        frame.repaint();
    }
    
//    public void showFinalScreen() {
//        frame.getContentPane().removeAll();
//
//        JPanel panel = new JPanel();
//        panel.setBounds(140, 240, 500, 100);
//        panel.setBackground(new Color(0, 0, 255, 142));
//        panel.setLayout(new BorderLayout());
//
//        JTextArea textArea = new JTextArea();
//        textArea.setEditable(false);
//        textArea.setFont(new Font("微软雅黑", Font.BOLD, 16));
//        textArea.setForeground(Color.WHITE);
//        textArea.setBackground(new Color(0, 0, 0, 0));
//        textArea.setFocusable(false);
//
//        JScrollPane scrollPane = new JScrollPane(textArea);
//        scrollPane.setOpaque(false);
//        scrollPane.getViewport().setOpaque(false);
//        panel.add(scrollPane, BorderLayout.CENTER);
//
//        String fullText = "恭喜! 你成功修复了系统! 现在可以绑定宿主开始对抗主神...";
//        Timer textTimer = new Timer(100, new ActionListener() {
//            int charIndex = 0;
//            @Override
//            public void actionPerformed(ActionEvent e) {
//                if (charIndex < fullText.length()) {
//                    textArea.setText(fullText.substring(0, charIndex + 1));
//                    charIndex++;
//                } else {
//                    ((Timer)e.getSource()).stop();
//                }
//            }
//        });
//        textTimer.start();
//
//        panel.addMouseListener(new MouseAdapter() {
//            @Override
//            public void mouseClicked(MouseEvent e) {
//                textTimer.stop();
//                showToBeContinued();
//            }
//        });
//
//        frame.add(panel);
//        frame.revalidate();
//        frame.repaint();
//    }
public void showFinalScreen() {
    frame.getContentPane().removeAll();
    frame.setLayout(null);  // 确保使用绝对布局

    JPanel panel = new JPanel();
    panel.setBounds(140, 240, 500, 100);
    panel.setBackground(new Color(0, 0, 255, 142));
    panel.setLayout(new BorderLayout());

    JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    textArea.setFont(new Font("微软雅黑", Font.BOLD, 16));
    textArea.setForeground(Color.WHITE);
    textArea.setBackground(new Color(0, 0, 0, 0));
    textArea.setFocusable(false);
    textArea.setEnabled(false);  // 防止拦截鼠标事件

    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setOpaque(false);
    scrollPane.getViewport().setOpaque(false);
    panel.add(scrollPane, BorderLayout.CENTER);

    String fullText = "恭喜! 你成功修复了系统! 现在可以绑定宿主开始对抗主神...";
    Timer textTimer = new Timer(100, new ActionListener() {
        int charIndex = 0;
        @Override
        public void actionPerformed(ActionEvent e) {
            if (charIndex < fullText.length()) {
                textArea.setText(fullText.substring(0, charIndex + 1));
                charIndex++;
            } else {
                ((Timer) e.getSource()).stop();
            }
        }
    });
    textTimer.start();

    // 统一的点击监听器
    MouseAdapter clickListener = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("Clicked!");  // 调试输出
            textTimer.stop();
            showToBeContinued();
        }
    };

    // 为所有组件添加监听
    panel.addMouseListener(clickListener);
    scrollPane.addMouseListener(clickListener);
    textArea.addMouseListener(clickListener);

    frame.add(panel);
    frame.revalidate();
    frame.repaint();
}
    
    public void showToBeContinued() {
        frame.getContentPane().removeAll();
        
        JLabel label = new JLabel("未完待续...", JLabel.CENTER);
        label.setFont(new Font("微软雅黑", Font.BOLD, 30));
        label.setForeground(Color.GRAY);
        label.setBounds(0, 0, 800, 600);
        
        frame.add(label);
        frame.revalidate();
        frame.repaint();
    }
    
    public void showLoadScreen() {
        frame.getContentPane().removeAll();
        
        JPanel panel = new JPanel();
        panel.setBounds(200, 150, 400, 400);
        panel.setBackground(new Color(0, 0, 100, 150));
        panel.setLayout(new BorderLayout());
        
        JLabel title = new JLabel("选择存档", JLabel.CENTER);
        title.setFont(new Font("微软雅黑", Font.BOLD, 20));
        title.setForeground(Color.WHITE);
        
        DefaultListModel<String> listModel = new DefaultListModel<>();
        for (String save : gameState.getSavedGames()) {
            listModel.addElement(save);
        }
        
        JList<String> saveList = new JList<>(listModel);
        saveList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        saveList.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        saveList.setForeground(Color.WHITE);
        saveList.setBackground(new Color(0, 0, 0, 0));
        
        JButton loadButton = ComponentFactory.createButton("加载", 0, 0, 100, 40);
        loadButton.setForeground(Color.BLACK);
        JButton deleteButton = ComponentFactory.createButton("删除", 0, 0, 100, 40);
        deleteButton.setForeground(Color.BLACK);
        JButton backButton = ComponentFactory.createButton("返回", 0, 0, 100, 40);
        backButton.setForeground(Color.BLACK);
        
        loadButton.addActionListener(e -> {
            String selected = saveList.getSelectedValue();
            if (selected != null) {
                JOptionPane.showMessageDialog(frame, "加载存档: " + selected);
                showRepairScreen(); // 实际游戏中会加载状态
            }
        });
        
        deleteButton.addActionListener(e -> {
            String selected = saveList.getSelectedValue();
            if (selected != null) {
                gameState.getSavedGames().remove(selected);
                listModel.removeElement(selected);
            }
        });
        
        backButton.addActionListener(e -> showMainMenu());
        
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(loadButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(backButton);
        buttonPanel.setBackground(new Color(0, 0, 0, 0));
        
        panel.add(title, BorderLayout.NORTH);
        panel.add(new JScrollPane(saveList), BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);
        
        frame.add(panel);
        frame.revalidate();
        frame.repaint();
    }
    
    public static void main(String[] args) {
        // 设置UI字体为中文
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.put("Button.font", new Font("微软雅黑", Font.PLAIN, 12));
            UIManager.put("Label.font", new Font("微软雅黑", Font.PLAIN, 12));
            UIManager.put("TextField.font", new Font("微软雅黑", Font.PLAIN, 12));
            UIManager.put("TextArea.font", new Font("微软雅黑", Font.PLAIN, 12));
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        SwingUtilities.invokeLater(() -> {
            CodeRebirthGame game = new CodeRebirthGame();
            game.showLoginScreen();
        });
    }

}
//1.如何重启系统?
//System.reboot();

//2.如何初始化内存?
//Memory mem = new Memory();
//mem.allocate();

//3.如何修复文件系统?
//FileSystem.recover(true);

//4.如何重置网络连接?
//Network.reset();

//5.如何恢复数据库?
//Database.restore();

//干扰主神
// god.override();  // 最简单的有效答案

